package com.qf.qflivehou.service.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.qflivehou.mapper.QfOrderDao;
import com.qf.qflivehou.mapper.repository.OrderRepository;
import com.qf.qflivehou.pojo.reqVo.OrderReq2;
import com.qf.qflivehou.pojo.respVo.ResponseData;
import com.qf.qflivehou.pojo.vo.QfCourse;
import com.qf.qflivehou.pojo.vo.QfOrder;
import com.qf.qflivehou.service.PayService;
import com.qf.qflivehou.service.UserService;
import com.qf.qflivehou.utils.AlipayUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author Mr.Liu
 * @date 2022/1/13 17:58
 */
@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private UserService userService;
    @Autowired
    private OrderRepository orderRepository;
    @Resource
    private QfOrderDao orderDao;
    @Autowired
    private AlipayUtils alipayUtils;
    private static Logger logger= LoggerFactory.getLogger(PayServiceImpl.class);

    @Override
    public ResponseData alipay(OrderReq2 orderReq2, HttpServletRequest request) {
        //校验用户登录状态
        ResponseData responseData = userService.findUserByToken(request);
        if(responseData.getCode()==1){
            return responseData;
        }
        //进行支付逻辑
        //1.使用前端传入的orderid从数据库中查询出该订单的数据
        Optional<QfOrder> byId = orderRepository.findById(orderReq2.getOrderid());
        if(!byId.isPresent()){
            return new ResponseData(1,"没有该订单,支付失败",null,null);
        }
        QfOrder qfOrder = byId.get();
        Map map = new HashMap();
        map.put("out_trade_no",qfOrder.getOrderid());//设置订单id
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",qfOrder.getOrderPay().toString());
        map.put("subject","课程购买");
        //查询出课程信息
        List<QfCourse> courses = orderDao.findCourseByOrderid(qfOrder.getOrderid());
        StringBuffer stringBuffer = new StringBuffer();
        for (QfCourse qfCourse : courses) {
            stringBuffer.append(qfCourse.getCourseName()+",");
        }
        map.put("body",stringBuffer.toString());
        //转换为json串
        String maps = JSONObject.toJSONString(map);
        try {
            String from = alipayUtils.alipayClient(maps);
            qfOrder.setOrderStatus(3);
            orderRepository.saveAndFlush(qfOrder);
            return new ResponseData(0,"请求支付成功",from,null);
        }catch (Exception e){
            return new ResponseData(1,"请求支付失败",null,null);
        }
    }

    @Override
    public void returnUrl(HttpServletRequest request) {
        //进行验签，判断是否是支付宝发给我们的请求
        boolean b = alipayUtils.notifyUrl(request);
        Map<String, String> map = AlipayUtils.convertRequestParamsToMap(request);
        //获取当前的订单id
        String out_trade_no = map.get("out_trade_no");
        Optional<QfOrder> byId = orderRepository.findById(out_trade_no);
        QfOrder qfOrder = byId.get();
        if(!b){
            logger.debug("校验失败");
            qfOrder.setOrderStatus(5);
            orderRepository.saveAndFlush(qfOrder);
            return;
        }else {
            logger.debug("验签成功");
            //验签成功,需要比对金额参数
            String total_amount = map.get("total_amount");
            //比对价格
            if(qfOrder.getOrderPay().compareTo((Double.valueOf(total_amount)))!=0){
                logger.debug("金额比对不通过");
                qfOrder.setOrderStatus(5);
            }else {
                logger.debug("金额比对成功");
                qfOrder.setOrderStatus(2);
            }
            //修改订单状态
            orderRepository.saveAndFlush(qfOrder);
        }
    }
}
